/* eslint-disable */
import Oidc from 'oidc-client';
// import 'babel-polyfill';
import store from '@/store'
import { MessageBox } from 'element-ui'

var mgr = new Oidc.UserManager({
  userStore: new Oidc.WebStorageStateStore(),
  authority: process.env.VUE_APP_AUTHSERVER_API,
  client_id: 'admin-client',
  redirect_uri: `${window.location.origin}/signin-oidc`,
  response_type: 'id_token token',
  scope: 'openid profile address email phone role offline_access Ape',
  post_logout_redirect_uri: window.location.origin + '/signout-callback-oidc',
  silent_redirect_uri: window.location.origin + '/silent-renew',
  accessTokenExpiringNotificationTime: 30,
  automaticSilentRenew: true,
  filterProtocolClaims: true,
  loadUserInfo: true
})

Oidc.Log.logger = console;
Oidc.Log.level = Oidc.Log.WARN;

mgr.events.addUserLoaded(function (user) {
  console.log('New User Loaded：', arguments);
  store.dispatch('auth/addToken', user)
});

mgr.events.addAccessTokenExpiring(function () {
  console.log('AccessToken Expiring：', arguments);
});

mgr.events.addAccessTokenExpired(function () {
  console.log('AccessToken Expired：', arguments);
  MessageBox.alert("登录已过期，请重新登录")
  mgr.signoutRedirect().then(function (resp) {
    console.log('signed out', resp);
  }).catch(function (err) {
    console.log(err)
  })
});

mgr.events.addSilentRenewError(function () {
  console.error('Silent Renew Error：', arguments);
});

mgr.events.addUserSignedOut(function () {
  MessageBox.alert("登录已过期，请重新登录")
  console.log('UserSignedOut：', arguments);
  mgr.signoutRedirect().then(function (resp) {
    console.log('signed out', resp);
  }).catch(function (err) {
    console.log(err)
  })
});

export default class SecurityService {

  // Renew the token manually
  renewToken() {
    let self = this
    return new Promise((resolve, reject) => {
      mgr.signinSilent().then(function (user) {
        if (user == null) {
          store.dispatch('auth/removeToken')
          self.signIn()
          return resolve(null)
        } else {
          store.dispatch('auth/addToken', user)
          return resolve(user)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }

  // Get the user who is logged in
  getUser() {
    let self = this
    return new Promise((resolve, reject) => {
      mgr.getUser().then(function (user) {             
        if (user == null) {
          store.dispatch('auth/removeToken')
          self.signIn()
          return resolve(null)
        } else {
          store.dispatch('auth/addToken', user)
          return resolve(user)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }

  // Redirect of the current window to the authorization endpoint.
  signIn() {
    mgr.signinRedirect().catch(function (err) {
      console.log(err)
    })
  }

  // Redirect of the current window to the end session endpoint
  signOut() {
    mgr.signoutRedirect().then(function (resp) {
      console.log('signed out', resp);
    }).catch(function (err) {
      console.log(err)
    })
  }

  // Get the profile of the user logged in
  getProfile() {
    let self = this
    return new Promise((resolve, reject) => {
      mgr.getUser().then(function (user) {
        if (user == null) {
          self.signIn()
          return resolve(null)
        } else {
          return resolve(user.profile)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }

  // Get the token id
  // getIdToken() {
  //   let self = this
  //   return new Promise((resolve, reject) => {
  //     mgr.getUser().then(function (user) {
  //       if (user == null) {
  //         self.signIn()
  //         return resolve(null)
  //       } else {
  //         return resolve(user.id_token)
  //       }
  //     }).catch(function (err) {
  //       console.log(err)
  //       return reject(err)
  //     });
  //   })
  // }

  // Get the session state
  // getSessionState() {
  //   let self = this
  //   return new Promise((resolve, reject) => {
  //     mgr.getUser().then(function (user) {
  //       if (user == null) {
  //         self.signIn()
  //         return resolve(null)
  //       } else {
  //         return resolve(user.session_state)
  //       }
  //     }).catch(function (err) {
  //       console.log(err)
  //       return reject(err)
  //     });
  //   })
  // }


  // Get the access token of the logged in user
  getUserWithoutSignIn() {
    let self = this
    return new Promise((resolve, reject) => {
      mgr.getUser().then(function (user) {
        if (user == null) {
          return resolve(null)
        } else {
          return resolve(user)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }

  // Get the access token of the logged in user
  // getAcessToken() {
  //   let self = this
  //   return new Promise((resolve, reject) => {
  //     mgr.getUser().then(function (user) {
  //       if (user == null) {
  //         self.signIn()
  //         return resolve(null)
  //       } else {
  //         return resolve(user.access_token)
  //       }
  //     }).catch(function (err) {
  //       console.log(err)
  //       return reject(err)
  //     });
  //   })
  // }

  // Takes the scopes of the logged in user
  getScopes() {
    let self = this
    return new Promise((resolve, reject) => {
      mgr.getUser().then(function (user) {
        if (user == null) {
          self.signIn()
          return resolve(null)
        } else {
          return resolve(user.scopes)
        }
      }).catch(function (err) {
        console.log(err)
        return reject(err)
      });
    })
  }

  // Get the user roles logged in
  // getRole() {
  //   let self = this
  //   return new Promise((resolve, reject) => {
  //     mgr.getUser().then(function (user) {
  //       if (user == null) {
  //         self.signIn()
  //         return resolve(null)
  //       } else {
  //         return resolve(user.profile.role)
  //       }
  //     }).catch(function (err) {
  //       console.log(err)
  //       return reject(err)
  //     });
  //   })
  // }
}